Learn to code for data analysis by The Open University

Learn to code for data analysis by The Open University

Author:The Open University [The Open University]
Language: eng
Format: epub
Publisher: The Open University
Published: 2019-12-31T16:00:00+00:00


Complete Exercise 2 in the Exercise notebook 3 to practise defining your own functions.

1.3 What if...?

The third conversion, from abbreviated country names to full names, can’t be written as a simple formula, because each abbreviation is expanded differently.

Figure 3

What I need is the Python code equivalent of:

if the name is ‘UK’, return ‘United Kingdom’,

otherwise if the name is ‘USA’, return ‘United States’,

otherwise return the name.

The last part basically says that if the name is none of the known abbreviations, return it unchanged. Translating the English sentence to Python is straightforward.

In []:

def expandCountry (name):

if name == 'UK': # if the name is 'UK'

return 'United Kingdom'

elif name == 'USA': # otherwise if the name is 'USA'

return 'United States'

else: # otherwise

return name

expandCountry('India') == 'India'

Out[]:

True

Note that ‘otherwise if’ is written 'elif' in Python, not 'else if' . As you might expect, ‘if’, ‘elif’ and ‘else’ are reserved words.

The computer will evaluate one condition at a time, from top to bottom, and execute only the instructions of the first condition that is true. Note that there is no condition after 'else' , it is a ‘catch all’ in case all previous conditions fail.

Note again the colons at the end of lines and that code after the colon must be indented. That is how Python distinguishes which lines of code belong to which condition.

There are almost always many ways to write the same function. A conditional statement does not need to have an 'elif' or 'else' part. In that case, if the condition is false, nothing happens. Here is the same function, written differently.

In []:

def expandCountry (name):

if name == 'UK':

name = 'United Kingdom'

if name == 'USA':

name = 'United States'

return name

You will see later this week an example of an ‘if-else’ statement, i.e. without the 'elif' part.

Exercise 3 What if…?



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.